< previous page page_159 next page >

Page 159
If you look closely at this code, you will see two separate subroutines. The first is the command button Click event routine. This routine will be executed when you click the command button. When you run this application you will see the first line being printed on the form and then a message box being displayed (see Figure 6.2). Until you click OK on the message box, the second Print statement in the main routine will not be executed.
12181-0159a.gif
Figure 6.2.
Displaying a message box in the called
subroutine will halt execution until
the message box is closed.
Looking at this very simple example, you could ask why not just put the line of code directly in the calling routine. In this instance, not only could you, but you should because a one-line subroutine is a very inefficient way to write code. However, if you are creating a task that requires many lines of code, using a subroutine would make your code a lot easier to understand.
When creating subroutines, you should keep the following things in mind:
Try to group related tasks into one subroutine.
If you have a task that is repetitive or will be called from many different places in the application, it should be created as a subroutine.
By keeping these in mind, you won't create many small subroutines that take action on the same group of information, such as a name and its related address, or retype the same section of code over and over again in different sections of the application. Another added benefit of using subroutines for complicated tasks is that if you must change the way it works, you would need to change it only in the subroutine. If you did not use a subroutine, you would need to search the entire application looking for the code to change.
Like any other procedure a subroutine starts at the top of its executable code and finishes at the bottom. If the subroutine must finish before it gets to the End Sub statement, you would add an Exit Sub statement to the code. This statement works just like the Exit

 
< previous page page_159 next page >

If you like this book, buy it!